package com.java.server;

import java.io.*;
import java.net.Socket;
import java.util.Properties;

class MyRunnable implements Runnable {
    Socket socket;
    Properties prop;

    public MyRunnable(Socket socket, Properties prop) {
        this.prop = prop;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while (true) {
                String choose = br.readLine();
                switch (choose) {
                    case "login" -> login(br);
                    case "register" -> register(br);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void register(BufferedReader br) throws IOException {
        String userinfo = br.readLine();
        String[] userInfoArr = userinfo.split("&");
        String usernameInput = userInfoArr[0].split("=")[1];
        String passwordInput = userInfoArr[1].split("=")[1];

        prop.put(usernameInput,passwordInput);

        FileWriter fw = new FileWriter("Info/userInfo.txt", true);
        fw.write("\n" + usernameInput + "=" + passwordInput);
        fw.flush();
        fw.close();
    }

    public void login(BufferedReader br) throws IOException {
        String userinfo = br.readLine();
        String[] userInfoArr = userinfo.split("&");
        String usernameInput = userInfoArr[0].split("=")[1];
        String passwordInput = userInfoArr[1].split("=")[1];

        if (prop.containsKey(usernameInput)) {
            String rightPassword = prop.get(usernameInput) + "";
            if (rightPassword.equals(passwordInput)) {
                writeMessage2Client("1");
                Server.list.add(socket);
                talk2All(br, usernameInput);
            } else {
                writeMessage2Client("2");
            }
        } else {
            writeMessage2Client("3");
        }
    }

    private void talk2All(BufferedReader br, String username) throws IOException {
        while (true) {
            String message = br.readLine();
            System.out.println(username + "：" + message);

            for (Socket s : Server.list) {
                writeMessage2Client(s, username + "：" + message);
            }
        }
    }

    //单播
    public void writeMessage2Client(String message) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(message);
        bw.newLine();
        bw.flush();
    }

    //广播（实际遍历服务端的socket）
    public void writeMessage2Client(Socket s, String message) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        bw.write(message);
        bw.newLine();
        bw.flush();
    }
}